﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using MvcApplicationDataHound.TSD_Mappings;
using NHibernate.Linq;

namespace MvcApplicationDataHound.Mappings
{
    public class TSD_ConsumeFile
    {
        //step7crudCreate
        public void CrudCreate(Make newMake)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.Save(newMake);
                    transaction.Commit();
                }
            }
        }

        //step8crudReadWlinq2nhibernate
        public Make CrudRead(Make searchMake)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                //var makeQuery = (from make in session.Query<Make>()
                //                 where make.Name == searchMake.Name
                //                 select make).Single();
                var makeQuery = (from make in session.Query<Make>()
                                 where make.Name == searchMake.Name
                                 select make).SingleOrDefault();

                return makeQuery;
            }
        }

        //step9crudUpdate
        public void CrudUpdate(Make originalMake, Make updatedMake)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                Make makeIPreparedEariler = session.Query<Make>()
                                                   .Where(m => m.Name == originalMake.Name)
                                                   .Select(m => m).Single();

                makeIPreparedEariler.Name = updatedMake.Name;

                //var Model = new Model();
                //Model.Make = makeIPreparedEariler;
                //Model.Name = "Ranger";
                //makeIPreparedEariler.Models.Add(Model);

                using (var transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(makeIPreparedEariler);
                    transaction.Commit();
                }
            }
        }

        //step10crudDelete
        public void CrudDelete(Make makeToDelete)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                Make makeIPreparedEariler = session.Query<Make>()
                                                   .Where(m => m.Name == makeToDelete.Name)
                                                   .Select(m => m).Single();

                using (var transaction = session.BeginTransaction())
                {
                    session.Delete(makeIPreparedEariler);
                    transaction.Commit();
                }
            }
        }

    }//EndClass
}//EndNameSpace